package com.example.ymm.modules1.service.dd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkhrm_1_0.Client;
import com.aliyun.dingtalkhrm_1_0.models.QueryHrmEmployeeDismissionInfoHeaders;
import com.aliyun.dingtalkhrm_1_0.models.QueryHrmEmployeeDismissionInfoRequest;
import com.aliyun.dingtalkhrm_1_0.models.QueryHrmEmployeeDismissionInfoResponse;
import com.aliyun.dingtalkhrm_1_0.models.QueryHrmEmployeeDismissionInfoResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListsimpleRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiUserListsimpleResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.example.ymm.exception.YmException;
import com.example.ymm.util.UtilValidate;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DdUserServer {

    /**
     * 钉钉用户信息查询
     */

    @Autowired
    AccessTokenService2 accessTokenService;


    /**
     * 通过手机号查询用户信息
     * @param mobile
     * @return
     */
    public JSONObject getUserInfoByMobile(String mobile){
        JSONObject json=null;
        String accessToken = accessTokenService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(mobile);
        try {
            OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);
            JSONObject result=JSONObject.parseObject(rsp.getBody());
            if("0".equals(result.getString("errcode"))){
                //请求成功
                 json=JSONObject.parseObject(result.getString("result"));
                System.out.println(result.getString("result"));
            }else{
                throw new YmException(result.getString("errmsg"));
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return json;
    }


    /**
     * 通过user_id 查询用户信息
     * @param userId
     * @return
     */
    public JSONObject getUserInfoByUserId(String userId){
        JSONObject json=null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            String accessToken = accessTokenService.getAccessToken();
            req.setUserid(userId);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, accessToken);
            JSONObject result=JSONObject.parseObject(rsp.getBody());

            if("0".equals(result.getString("errcode"))){
                json=JSONObject.parseObject(result.getString("result"));
            }else{
               // throw new YmException(result.getString("errmsg"));
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 获取部门用户信息
     * https://open.dingtalk.com/document/orgapp/queries-the-simple-information-of-a-department-user
     * @return
     */
    public JSONObject getDeptUserList(){
        JSONObject json=null;
        String accessToken = accessTokenService.getAccessToken();

        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listsimple");
            OapiUserListsimpleRequest req = new OapiUserListsimpleRequest();
            req.setDeptId(1L);
            req.setCursor(0L);
            req.setSize(100L);
            req.setOrderField("modify_desc");
            req.setContainAccessLimit(false);
            req.setLanguage("zh_CN");
            OapiUserListsimpleResponse rsp = client.execute(req, accessToken);
//            System.out.println(rsp.getBody());
            JSONObject responseBodyJson= JSON.parseObject(rsp.getBody());
            if("0".equals(responseBodyJson.getString("errcode"))){
                json=responseBodyJson.getJSONObject("result");
            }else{
                throw new YmException(responseBodyJson.getString("errmsg"));
            }
        }catch (ApiException e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }


        return json;
    }


    /**
     * 获取部门信息
     * https://open.dingtalk.com/document/orgapp/queries-the-simple-information-of-a-department-user
     * deptId 1l
     * @return
     */
    public JSONArray getDeptList(long deptId){
        JSONArray json=null;
        String accessToken = accessTokenService.getAccessToken();

        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(deptId);
            req.setLanguage("zh_CN");
            OapiV2DepartmentListsubResponse rsp = client.execute(req, accessToken);
//            System.out.println(rsp.getBody());
            JSONObject responseBodyJson= JSON.parseObject(rsp.getBody());
            if("0".equals(responseBodyJson.getString("errcode"))){
                json=responseBodyJson.getJSONArray("result");
            }else{
                throw new YmException(responseBodyJson.getString("errmsg"));
            }
        }catch (ApiException e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }


        return json;
    }

    /**
     * 获取部门-成员 列表
     * https://open.dingtalk.com/document/orgapp/queries-the-simple-information-of-a-department-user
     * deptId 1l
     * @return
     */
    public JSONObject getDeptUserList(long deptId){
        JSONObject json=null;
        String accessToken = accessTokenService.getAccessToken();

        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listsimple");
            OapiUserListsimpleRequest req = new OapiUserListsimpleRequest();
            req.setDeptId(deptId);
            req.setCursor(0L);
            req.setSize(100L);
            req.setOrderField("modify_desc");
            req.setContainAccessLimit(false);
            req.setLanguage("zh_CN");
            OapiUserListsimpleResponse rsp = client.execute(req, accessToken);
            JSONObject responseBodyJson= JSON.parseObject(rsp.getBody());
            if("0".equals(responseBodyJson.getString("errcode"))){
                json=responseBodyJson.getJSONObject("result");
            }else{
                throw new YmException(responseBodyJson.getString("errmsg"));
            }
        }catch (ApiException e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }


        return json;
    }


    /**
     * 获取所有的部门列表
     * @return
     */
    public JSONArray getAllDeptList(){
        //最上级部门列表
        JSONArray deptList = getDeptList(1l);
        for (int i = 0; i < deptList.size(); i++) {
            JSONObject jsonObject = deptList.getJSONObject(i);
            forEachDeptList(jsonObject);
        }
        return deptList;
    }

    public void forEachDeptList(JSONObject item){
        JSONArray children = getDeptList(item.getLong("dept_id"));
        if(UtilValidate.isNotEmpty(children)){
            item.put("children",children);
            for (int i = 0; i < children.size(); i++) {
                JSONObject jsonObject = children.getJSONObject(i);
                forEachDeptList(jsonObject);
            }
        }

    }



    public  List<String> getDimissionUserList(List<String> list){

        JSONObject json=null;
        List<String> strs=new ArrayList<>();
        String accessToken = accessTokenService.getAccessToken();
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        QueryHrmEmployeeDismissionInfoHeaders queryHrmEmployeeDismissionInfoHeaders = new QueryHrmEmployeeDismissionInfoHeaders();
        queryHrmEmployeeDismissionInfoHeaders.xAcsDingtalkAccessToken = accessToken;
        QueryHrmEmployeeDismissionInfoRequest queryHrmEmployeeDismissionInfoRequest = new QueryHrmEmployeeDismissionInfoRequest()
                .setUserIdList(list);
        try {
            Client client = new Client(config);

            QueryHrmEmployeeDismissionInfoResponse queryInfoResponse = client.queryHrmEmployeeDismissionInfoWithOptions(queryHrmEmployeeDismissionInfoRequest, queryHrmEmployeeDismissionInfoHeaders, new RuntimeOptions());
            List<QueryHrmEmployeeDismissionInfoResponseBody.QueryHrmEmployeeDismissionInfoResponseBodyResult> result = queryInfoResponse.getBody().getResult();
//            System.out.println("--离职员工信息"+result);
            for(QueryHrmEmployeeDismissionInfoResponseBody.QueryHrmEmployeeDismissionInfoResponseBodyResult bodyResult : result){
                if(bodyResult.getStatus()==2){
                    strs.add(bodyResult.getUserId());
                }
            }
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new YmException(err.message);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new YmException(err.message);

            }

        }
        return strs;
    }





}
